package org.example.blog.config;

import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.example.blog.utils.JwtUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@ControllerAdvice
public class LoginInterceptor implements HandlerInterceptor {

    // 进行用户登录校验
    // 1.从header中获取token
    // 2. 验证token
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("user_token");
        log.info("从header中获取token, token:"+token);
        Claims claims = JwtUtils.parseToken(token);

        if (claims==null){
            //token是不合法的
            response.setStatus(401);
            return false;
        }
        return true;

    }
}
